package com.example.demo.controller;

import com.example.demo.entity.CourseMaterialBean;
import com.example.demo.service.CourseMaterialService;
import com.example.demo.util.PageEntity;
import com.example.demo.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/course/material")
public class CourseMaterialController {

    @Autowired
    private CourseMaterialService courseMaterialService;

    @GetMapping("/all")
    public List<CourseMaterialBean> getAll() {
        return courseMaterialService.all();
    }
    
    @GetMapping("/course/{courseId}")
    public List<CourseMaterialBean> getByCourseId(@PathVariable Integer courseId) {
        return courseMaterialService.getByCourseId(courseId);
    }

    @PostMapping("/add")
    public ResponseEntity add(@RequestBody CourseMaterialBean courseMaterialBean) {
        Integer result = courseMaterialService.add(courseMaterialBean);
        if (result > 0) {
            return ResponseEntity.success("新增成功");
        } else {
            return ResponseEntity.failed("新增失败");
        }
    }

    @PostMapping("/edit")
    public ResponseEntity edit(@RequestBody CourseMaterialBean courseMaterialBean) {
        Integer result = courseMaterialService.update(courseMaterialBean);
        if (result > 0) {
            return ResponseEntity.success("修改成功");
        } else {
            return ResponseEntity.failed("修改失败");
        }
    }

    @GetMapping("/del")
    public ResponseEntity del(@RequestParam("id") Integer id) {
        Integer result = courseMaterialService.delete(id);
        if (result > 0) {
            return ResponseEntity.success("删除成功");
        } else {
            return ResponseEntity.failed("删除失败");
        }
    }

    @GetMapping("/get/{id}")
    public CourseMaterialBean getOne(@PathVariable Integer id) {
        return courseMaterialService.one(id);
    }

    /**
     * 分页查询课程资料
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @param name 资料名称
     * @param courseId 课程ID
     * @param sort 排序字段
     * @param order 排序方式 desc、asc
     * @return 分页结果
     */
    @GetMapping("/list")
    public ResponseEntity list(
            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", defaultValue = "") String name,
            @RequestParam(value = "courseId", required = false) Integer courseId,
            @RequestParam(value = "sort", defaultValue = "id") String sort,
            @RequestParam(value = "order", defaultValue = "desc") String order
    ) {
        String sortOrder = sort + " " + order;
        PageEntity list = courseMaterialService.list(pageNo, pageSize, name, courseId, sortOrder);
        return new ResponseEntity<>(200, null, list);
    }
}
